import { SystemInterface, MethodDescriptor } from './Scanner';
import { ProtocolType } from '../core/interfaces';

export interface MappingRule {
    match(interface: SystemInterface, method: MethodDescriptor): boolean;
    mapToProtocol(): ProtocolType;
    generateAdapterMethod(method: MethodDescriptor): string;
}

export class DefaultRuleEngine {
    private rules: MappingRule[] = [];

    registerRule(rule: MappingRule) {
        this.rules.push(rule);
    }

    findMatchingRule(interface: SystemInterface, method: MethodDescriptor): MappingRule | null {
        return this.rules.find(rule => rule.match(interface, method)) || null;
    }

    static createDefault(): DefaultRuleEngine {
        const engine = new DefaultRuleEngine();
        
        // 注册默认规则
        engine.registerRule({
            match: (intf, method) => intf.type === 'COM' && method.returnType === 'HRESULT',
            mapToProtocol: () => ProtocolType.PROCESS,
            generateAdapterMethod: (method) => `
                ${method.name}(${method.parameters.map(p => `${p.name}: ${p.type}`).join(', ')}): Promise<${method.returnType}> {
                    return this.executeComMethod('${method.name}', { ${method.parameters.map(p => p.name).join(', ')} });
                }
            `
        });

        // 添加更多默认规则...
        return engine;
    }
}

export class AdapterGenerator {
    constructor(private ruleEngine: DefaultRuleEngine) {}

    generateAdapter(interface: SystemInterface): string {
        let classCode = `import { ICompatibleAdapter, AdapterInfo } from '../core/interfaces';\n\n`;
        classCode += `export class Dynamic${interface.name}Adapter implements ICompatibleAdapter {\n`;
        
        // 生成getInfo方法
        classCode += `    getInfo(): AdapterInfo {\n`;
        classCode += `        return {\n`;
        classCode += `            name: 'Dynamic${interface.name}Adapter',\n`;
        classCode += `            version: '1.0.0',\n`;
        classCode += `            target: '${interface.type}',\n`;
        classCode += `            description: 'Dynamically generated adapter for ${interface.name}'\n`;
        classCode += `        };\n`;
        classCode += `    }\n\n`;

        // 生成接口方法
        for (const method of interface.methods) {
            const rule = this.ruleEngine.findMatchingRule(interface, method);
            if (rule) {
                classCode += rule.generateAdapterMethod(method);
                classCode += '\n\n';
            }
        }

        classCode += '}\n';
        return classCode;
    }
}